const crypto = require('crypto')
class WeiXinController {
    static async wxToken(ctx) {
        const token = 'lsdfly', // 自定义，与公众号设置的一致
            signature = ctx.query.signature,
            timestamp = ctx.query.timestamp,
            nonce = ctx.query.nonce
            // 字典排序
        const arr = [token, timestamp, nonce].sort()

        const sha1 = crypto.createHash('sha1')
        sha1.update(arr.join(''))
        const result = sha1.digest('hex')
       console.log('get:',result)
        if (result === signature) {
            ctx.body = ctx.query.echostr
        } else {
            ctx.body = { code: -1, msg: "fail" }
        }
    }
    static async notice(ctx) {
       
        let promise = new Promise(function(resolve, reject) {
            let buf = ''
            ctx.req.setEncoding('utf8')
            ctx.req.on('data', (chunk) => {
                buf += chunk
            })
            ctx.req.on('end', () => { 
                //  xml.xmlToJson(buf)
                    //.then(resolve)
                  //  .catch(reject)
                  resolve(buf)
            })
        })

        await promise.then((result) => {
            console.log('微信信息进来了')
            console.log(result);
                ctx.body = `
                <xml><ToUserName><![CDATA[oAOM7uCXcqFFBCKVVGwnW72WIsek]]></ToUserName>
                <FromUserName><![CDATA[gh_1315d187ef88]]></FromUserName>
                <CreateTime>1524150808</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[验证码]]></Content>
                <MsgId>6546177874998888649</MsgId>
                </xml>`
                // ctx.res.setHeader('Content-Type', 'application/xml')
                // ctx.res.end(result)
            })
            .catch((e) => {
                e.status = 400
            })


      //  ctx.body = 'dasd';
    }
}
export default WeiXinController;